package cn.kgm.makeGodV2.ruleEngine;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Version 1.8
 * @Author: Kappi
 * @Date: 2025-9-25 11:26
 * @Description: cn.kgm.makeGodV2.ruleEngine.SimpleRuleEngine
 */
public class SimpleRuleEngine {
    private static SimpleRuleEngine instance;
    private final Map<String, RuleStrategy<?>> ruleStrategyMap = new HashMap<>();

    private SimpleRuleEngine() {
        // 注册原子规则
        registerRule(new RealmCheckRule());
        registerRule(new SingleItemCheckRule());
        registerRule(new RandomTriggerRule());

        // 注册逻辑操作符规则
        registerRule(new AndConditionRule());
        registerRule(new OrConditionRule());
        registerRule(new NotConditionRule());
//        registerRule(new XorConditionRule());
    }

    public static SimpleRuleEngine getInstance() {
        if (instance == null) {
            instance = new SimpleRuleEngine();
        }
        return instance;
    }

    public void registerRule(RuleStrategy<?> ruleStrategy) {
        String ruleType = ruleStrategy.getRuleType();
        if (ruleStrategyMap.containsKey(ruleType)) {
            System.out.println("警告: 规则类型 " + ruleType + " 已存在，将被覆盖");
        }
        ruleStrategyMap.put(ruleType, ruleStrategy);
        System.out.println("注册规则: " + ruleType);
    }

    @SuppressWarnings("unchecked")
    public <T> RuleStrategy<T> getRuleStrategy(String ruleType) {
        RuleStrategy<?> strategy = ruleStrategyMap.get(ruleType);
        if (strategy == null) {
            throw new IllegalArgumentException("未找到规则策略: " + ruleType);
        }
        return (RuleStrategy<T>) strategy;
    }

    public <T> RuleResult<T> executeRule(String ruleType, RuleContext context) {
        try {
            RuleStrategy<T> strategy = getRuleStrategy(ruleType);

            if (!strategy.validate(context)) {
                return RuleResult.fail("规则条件不满足: " + ruleType);
            }

            return strategy.execute(context);
        } catch (Exception e) {
            return RuleResult.fail("规则执行异常: " + e.getMessage());
        }
    }

    /**
     * 执行复杂条件配置
     */
    public RuleResult<Boolean> executeComplexCondition(ConditionConfig condition, RuleContext context) {
        return ConditionExecutor.executeCondition(condition, context);
    }

    /**
     * 获取所有已注册的规则类型
     */
    public Set<String> getRegisteredRuleTypes() {
        return new HashSet<>(ruleStrategyMap.keySet());
    }
}
